import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
    getChatConversationsAPI,
    getChatMessagesAPI,
    sendChatMessageAPI,
    markMessagesAsReadAPI,
    getOnlineUsersAPI,
    searchUsersAPI,
    createConversationAPI,
    type ChatConversation,
    type ChatMessage,
    type ChatUser
} from '@/api/chat'
import { wsService } from '@/utils/websocket'
import { useAuthStore } from '@/stores/auth'

export const useChatStore = defineStore('chat', () => {
    // 状态
    const conversations = ref<ChatConversation[]>([])
    const currentMessages = ref<ChatMessage[]>([])
    const currentChatUser = ref<ChatUser | null>(null)
    const onlineUsers = ref<ChatUser[]>([])
    const searchResults = ref<ChatUser[]>([])
    const isLoading = ref(false)
    const isConnected = ref(false)
    const unreadTotalCount = ref(0)

    // 计算属性
    const sortedConversations = computed(() => {
        return [...conversations.value].sort((a, b) => {
            const aTime = new Date(a.updated_at).getTime()
            const bTime = new Date(b.updated_at).getTime()
            return bTime - aTime
        })
    })

    const currentChatUnreadCount = computed(() => {
        if (!currentChatUser.value) return 0
        const conversation = conversations.value.find(
            conv => conv.other_user_id === currentChatUser.value!.id
        )
        return conversation?.unread_count || 0
    })

    // 方法
    const loadConversations = async () => {
        try {
            isLoading.value = true
            const response = await getChatConversationsAPI()
            // 适配后端数据格式
            const rawConversations = response.data?.chats || response.data || []
            conversations.value = rawConversations.map((conv: any) => {
                // 转换后端格式到前端格式
                const authStore = useAuthStore()
                const otherUser = conv.user1?.id === authStore.userInfo?.id ? conv.user2 : conv.user1
                return {
                    id: conv.id,
                    user_id: authStore.userInfo?.id,
                    other_user_id: otherUser?.id,
                    other_user: otherUser,
                    last_message: conv.last_message ? {
                        id: conv.last_message.id,
                        sender_id: conv.last_message.sender_id,
                        content: conv.last_message.content,
                        type: conv.last_message.type,
                        message_type: conv.last_message.type, // 兼容性
                        sent_at: conv.last_message.sent_at,
                        created_at: conv.last_message.sent_at, // 兼容性
                        is_read: !!conv.last_message.read_at, // 根据read_at计算
                        read_at: conv.last_message.read_at,
                        status: conv.last_message.status
                    } : undefined,
                    unread_count: conv.unread_count || 0,
                    updated_at: conv.last_message_at || conv.updated_at
                }
            })
            updateUnreadTotalCount()
        } catch (error) {
            console.error('加载聊天列表失败:', error)
        } finally {
            isLoading.value = false
        }
    }

    const loadMessages = async (otherUserId: number, page = 1, pageSize = 50) => {
        try {
            isLoading.value = true
            const response = await getChatMessagesAPI({
                other_user_id: otherUserId,
                page,
                page_size: pageSize
            })
            const rawMessages = response.data?.messages || []
            // 适配后端数据格式
            const messages = rawMessages.map((msg: any) => ({
                id: msg.id,
                sender_id: msg.sender_id,
                receiver_id: otherUserId, // 当前用户是接收者
                chat_id: msg.chat_id,
                content: msg.content,
                type: msg.type,
                message_type: msg.type, // 兼容性
                sent_at: msg.sent_at,
                created_at: msg.sent_at, // 兼容性
                read_at: msg.read_at,
                is_read: !!msg.read_at, // 根据read_at计算
                status: msg.status,
                sender: msg.sender
            }))

            if (page === 1) {
                currentMessages.value = messages.reverse()
            } else {
                currentMessages.value = [...messages.reverse(), ...currentMessages.value]
            }
        } catch (error) {
            console.error('加载消息失败:', error)
        } finally {
            isLoading.value = false
        }
    }

    const sendMessage = async (receiverId: number, content: string, messageType: 'text' | 'image' | 'file' = 'text') => {
        try {
            // 先通过WebSocket发送消息（实时）
            if (wsService.getConnectionState() === 'connected') {
                wsService.sendMessage(receiverId, content, messageType)
            }

            // 同时通过API发送消息（确保消息持久化）
            const response = await sendChatMessageAPI({
                receiver_id: receiverId,
                content,
                type: messageType,
                message_type: messageType // 兼容性
            })
            const rawMessage = response.data
            // 适配后端数据格式
            const newMessage = {
                id: rawMessage.id,
                sender_id: rawMessage.sender_id,
                receiver_id: receiverId,
                chat_id: rawMessage.chat_id,
                content: rawMessage.content,
                type: rawMessage.type,
                message_type: rawMessage.type, // 兼容性
                sent_at: rawMessage.sent_at,
                created_at: rawMessage.sent_at, // 兼容性
                read_at: rawMessage.read_at,
                is_read: !!rawMessage.read_at,
                status: rawMessage.status,
                sender: rawMessage.sender
            }
            currentMessages.value.push(newMessage)

            // 更新对话列表中的最后一条消息
            updateConversationLastMessage(receiverId, newMessage)

            return newMessage
        } catch (error) {
            console.error('发送消息失败:', error)
            throw error
        }
    }

    const markMessagesAsRead = async (otherUserId: number) => {
        try {
            await markMessagesAsReadAPI(otherUserId)

            // 更新本地状态
            const conversation = conversations.value.find(conv => conv.other_user_id === otherUserId)
            if (conversation) {
                conversation.unread_count = 0
            }

            // 更新消息状态
            currentMessages.value.forEach(message => {
                if (message.sender_id === otherUserId) {
                    message.is_read = true
                }
            })

            updateUnreadTotalCount()
        } catch (error) {
            console.error('标记消息为已读失败:', error)
        }
    }

    const loadOnlineUsers = async () => {
        try {
            const response = await getOnlineUsersAPI()
            onlineUsers.value = response.data || []
        } catch (error) {
            console.error('加载在线用户失败:', error)
        }
    }

    const searchUsers = async (keyword: string) => {
        try {
            if (!keyword.trim()) {
                searchResults.value = []
                return
            }
            const response = await searchUsersAPI(keyword)
            searchResults.value = response.data || []
        } catch (error) {
            console.error('搜索用户失败:', error)
        }
    }

    const createConversation = async (otherUserId: number) => {
        try {
            const response = await createConversationAPI(otherUserId)
            await loadConversations()
            return response.data
        } catch (error) {
            console.error('创建对话失败:', error)
            throw error
        }
    }

    const setCurrentChatUser = (user: ChatUser | null) => {
        currentChatUser.value = user
        if (user) {
            loadMessages(user.id)
            markMessagesAsRead(user.id)
        } else {
            currentMessages.value = []
        }
    }

    const addMessage = (message: any) => {
        // 适配WebSocket消息格式
        const adaptedMessage = {
            id: message.id || message.message_id,
            sender_id: message.sender_id,
            receiver_id: message.receiver_id,
            content: message.content,
            type: message.type || message.message_type || 'text',
            message_type: message.type || message.message_type || 'text', // 兼容性
            sent_at: message.sent_at || message.created_at,
            created_at: message.sent_at || message.created_at, // 兼容性
            read_at: message.read_at,
            is_read: !!message.read_at,
            status: message.status || 'sent',
            sender: message.sender
        }

        // 如果是当前聊天用户的消息，直接添加到当前消息列表
        if (currentChatUser.value &&
            (adaptedMessage.sender_id === currentChatUser.value.id ||
                adaptedMessage.receiver_id === currentChatUser.value.id)) {
            currentMessages.value.push(adaptedMessage)
        }

        // 更新对话列表
        updateConversationLastMessage(
            adaptedMessage.sender_id === currentChatUser.value?.id ? adaptedMessage.receiver_id : adaptedMessage.sender_id,
            adaptedMessage
        )
    }

    const updateConversationLastMessage = (otherUserId: number, message: ChatMessage) => {
        const conversation = conversations.value.find(conv => conv.other_user_id === otherUserId)
        if (conversation) {
            conversation.last_message = message
            conversation.updated_at = message.created_at

            // 如果不是当前聊天用户且消息不是自己发送的，增加未读数
            if (currentChatUser.value?.id !== otherUserId && message.sender_id !== currentChatUser.value?.id) {
                conversation.unread_count++
            }
        } else {
            // 创建新对话
            conversations.value.push({
                id: Date.now(), // 临时ID
                user_id: 0, // 将在API响应中更新
                other_user_id: otherUserId,
                last_message: message,
                unread_count: currentChatUser.value?.id !== otherUserId ? 1 : 0,
                updated_at: message.created_at,
                other_user: onlineUsers.value.find(user => user.id === otherUserId) || {
                    id: otherUserId,
                    username: '未知用户',
                    role: 'unknown'
                }
            })
        }

        updateUnreadTotalCount()
    }

    const updateUnreadTotalCount = () => {
        unreadTotalCount.value = conversations.value.reduce((total, conv) => total + conv.unread_count, 0)
    }

    const clearCurrentChat = () => {
        currentChatUser.value = null
        currentMessages.value = []
    }

    // WebSocket连接管理
    const connectWebSocket = () => {
        wsService.connect()
    }

    const disconnectWebSocket = () => {
        wsService.disconnect()
    }

    const sendTypingStatus = (receiverId: number, isTyping: boolean) => {
        if (wsService.getConnectionState() === 'connected') {
            wsService.sendTyping(receiverId, isTyping)
        }
    }

    return {
        // 状态
        conversations,
        currentMessages,
        currentChatUser,
        onlineUsers,
        searchResults,
        isLoading,
        isConnected,
        unreadTotalCount,

        // 计算属性
        sortedConversations,
        currentChatUnreadCount,

        // 方法
        loadConversations,
        loadMessages,
        sendMessage,
        markMessagesAsRead,
        loadOnlineUsers,
        searchUsers,
        createConversation,
        setCurrentChatUser,
        addMessage,
        clearCurrentChat,
        connectWebSocket,
        disconnectWebSocket,
        sendTypingStatus
    }
})
